<?php
/**
 * Created by PhpStorm.
 * User: seven
 * Date: 2018/3/27
 * Time: 下午11:35
 */

class Resp
{

    const RESPONSE_OK = 0;

    public static function redirect($url, $flashName=null, array $flashData=null){
        if($flashName != null) Lang2::flashSet($flashName, $flashData);
        Lang2::setHeader("Location", $url);
    }

    public static function response_content($code, $content){
        http_response_code($code);
        echo $content;
    }

    public static function response_json_fail($code, $message = '') {
        if(!(is_numeric($code))) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
        );

        return json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    public static function response_json_ok($data = array()) {

        $result = array(
            'code' => self::RESPONSE_OK,
            'data' => $data
        );

        return json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    public static function response_json($code, $message = '', $data = array()) {
        if(!(is_numeric($code))) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );

        return json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    public static function response_xml($code, $message = '', $data = array()) {
        if(!is_numeric($code)) {
            return '';
        }

        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );

        header('Content-Type:text/xml');
        $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
        $xml .= "<root>";
        $xml .= self::xmlToEncode($result);
        $xml .= "</root>";
        return $xml;
    }

    private static  function xmlToEncode($result) {
        $xml = $attr = '';
        foreach($result as $key => $value) {
            if(is_numeric($key)) {
                $attr = " id='" . $key . "'";
                $key = "item";
            }
            $xml .= "<{$key}{$attr}>";
            $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
            $xml .= "</{$key}>\n";
        }
        return $xml;
    }

}